package com.srx.elasticsearch.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.srx.openfeign.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * 用户服务类
 * <p>用于处理与用户相关的业务逻辑，该类提供了多个方法，用于通过不同的查询条件从Elasticsearch中获取用户信息，并处理可能发生的I/O异常。</p>
 * @author 沈汝旭
 * @since 2025-10-18 10:54:05
 * @version 1.0
 */
@Service
public class UserService
{

    /**
	 * Elasticsearch客户端对象
	 */
    private final ElasticsearchClient client;


    /**
	 * 构造函数，注入Elasticsearch客户端对象
	 * @param client Elasticsearch客户端对象
	 */
	@Autowired
	public UserService(ElasticsearchClient client)
	{
		this.client = client;
	}
	
	

	/**
	 * 根据账号获取用户ID
	 * @param account 账户名
	 * @return 用户ID
	 */
	public Long getUserIdByAccount(String account) throws IOException
	{
		SearchResponse<UserDTO> search = client.search(s -> s
						.index("user")
						.query(q -> q
								.term(t -> t
										.field("account")
										.value(account)))
						.source(sf -> sf
								.filter(f -> f
										.includes("id")))
				, UserDTO.class);
        //返回用户ID
        if (!search.hits().hits().isEmpty())
        {
            return Objects.requireNonNull(search.hits().hits().getFirst().source()).getId();
        }
        else
        {
            return 0L;
        }
	}
	
	
	/**
	 * 根据邮箱获取用户ID
	 * @param email 邮箱
	 * @return 用户ID
	 */
	public Long getUserIdByEmail(String email) throws IOException
	{
		SearchResponse<UserDTO> search = client.search(s -> s
						.index("user")
						.query(q -> q
								.term(t -> t
										.field("email")
										.value(email)))
						.source(sf -> sf
								.filter(f -> f
										.includes("id")))
				, UserDTO.class);
		if (!search.hits().hits().isEmpty())
		{
			return Objects.requireNonNull(search.hits().hits().getFirst().source()).getId();
		}
		else
		{
			return 0L;
		}
	}
	
}
